package utils

import (
	"database/sql"
	"fmt"
	_ "github.com/go-sql-driver/mysql"
	"github.com/spf13/viper"
)

type MysqlClient struct {
	Name   string
	Client *sql.DB
	Config *MysqlConfig
}
type MysqlConfig struct {
	username string
	//连接数据库的密码
	password string
	//连接数据库的地址
	ip string
	//连接数据库的端口号
	port int
	//连接数据库的具体数据库名称
	dbname string
	//连接数据库的编码格式
	charset string
}

func MysqlConf() *MysqlConfig {
	return &MysqlConfig{
		username: viper.GetString("db.mysql.conf.username"),
		//连接数据库的密码
		password: viper.GetString("db.mysql.conf.password"),
		//连接数据库的地址
		ip: viper.GetString("db.mysql.conf.ip"),
		//连接数据库的端口号
		port: viper.GetInt("db.mysql.conf.port"),
		//连接数据库的具体数据库名称
		dbname: viper.GetString("db.mysql.conf.dbname"),
		//连接数据库的编码格式
		charset: viper.GetString("db.mysql.conf.charset"),
	}
}

func NewMysqlClient(name string, conf *MysqlConfig) *MysqlClient {
	if conf == nil {
		conf = MysqlConf()
	}
	//client :=DB(userName string, password string, ipAddress string, port int, dbName string, charset string)
	client := &MysqlClient{Name: name, Config: conf}
	_, err := client.DB(conf.username, conf.password, conf.ip, conf.port, conf.dbname, conf.charset)
	if err != nil {
		return nil
	}
	return client
}

func (this *MysqlClient) DB(userName string, password string, ipAddress string, port int, dbName string, charset string) (db *sql.DB, err error) {
	dsn := fmt.Sprintf("%s:%s@tcp(%s:%d)/%s?charset=%s", userName, password, ipAddress, port, dbName, charset)
	//Open打开一个driverName指定的数据库，dataSourceName指定数据源
	//不会校验用户名和密码是否正确，只会对dsn的格式进行检测
	db, err = sql.Open("mysql", dsn)
	this.Client = db
	if err != nil { //dsn格式不正确的时候会报错
		return db, err
	}
	//尝试与数据库连接，校验dsn是否正确
	err = db.Ping()
	if err != nil {
		fmt.Println("校验失败,err", err)
		return db, err
	}
	// 设置最大连接数
	db.SetMaxOpenConns(1)
	// 设置最大的空闲连接数
	// db.SetMaxIdleConns(20)
	fmt.Println("连接数据库成功！")
	return db, nil
}
